﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Sausage.Web.Domain;

namespace Sausage.Web.Models
{
    public class MenuViewModel
    {
        public string GetMenuHtml()
        {
            StringBuilder builder = new StringBuilder();
            var list = Helper.CurrentPrincipal.MeanList;
            if (list == null || list.Count == 0)
                return string.Empty;
            
            int menuGroup = 0;
            for (int i = 0; i < list.Count; i++)
            {
                MenuInfo next = null;
                MenuInfo current = list[i];
                MenuInfo previous = null;
                
                if(i>0)
                    previous = list[i - 1];
                if(i<list.Count - 1)
                    next = list[i + 1];

                bool firstRow = false;
                bool lastRow = false;
                string menuClass = string.Empty;
                
                if (previous == null || (current.Category != previous.Category)) //the first or the category change.
                {
                    menuGroup++;
                    builder.AppendFormat(
                        "<div id=\"{0}\"><p><span>{1}</span><span class='menuRightButton menuRightButtonUp' data-group='" + menuGroup + "'></span></p></div>",
                        previous == null ? "menutitle_first" : "menutitle",
                        list[i].Category.CategoryName);
                    firstRow = true;
                }

                if(next == null || (current.Category != next.Category)) // the last or the category change at next.
                    lastRow = true;

                if (firstRow)
                    builder.Append("<ul data-group='" + menuGroup +"'>");

                if (firstRow || lastRow)
                    menuClass = string.Format(" class=\"{0}\"", ((firstRow && lastRow) ? "last first" : (firstRow ? "first" : "last")));

                builder.AppendFormat("<li{0}><a href=\"{1}\">{2}</a></li>", menuClass, current.Menu.SourceUrl, current.Menu.MenuName);

                if (lastRow)
                    builder.Append("</ul>");
            }

            return builder.ToString();
        }
    }
}